package algorithm.leetcode.simple;

/**
 * 给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
 */

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/11/9
 */
public class Question637 {

    public static void main(String[] args) {

        Question637 question = new Question637();
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        List<Double> average = question.averageOfLevels(root);
        System.out.println(average);
    }

    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> res = new ArrayList<>(10);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        double sum;
        int size;
        while (!queue.isEmpty()) {
            sum = 0;
            size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                sum += node.val;
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            res.add(sum / size);
        }
        return res;
    }

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
